import style from "./index.module.css";
import { getGameListApi } from "@/apis/game";
import { message, Spin, Row, Col, Select, Input, Tabs } from "antd";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { getCategoryListApi } from "@/apis/category";

const { Option } = Select;
const { Search } = Input;

export default function GameList() {
  const [gameList, setGameList] = useState([]);
  const [filteredGames, setFilteredGames] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("all");
  const [sortOption, setSortOption] = useState("popular");
  const navigate = useNavigate();

  // 模拟游戏分类数据 - 实际应从API获取
  const [gameCategoryList, setGameCategoryList] = useState([]);

  // 转换为Tabs所需的items格式
  const categoryItems = gameCategoryList.map((category: any) => ({
    key: category.id,
    label: category.categoryName,
  }));

  async function getGameList() {
    try {
      setLoading(true);
      const res: any = await getGameListApi({ page: 1, size: 20 });
      if (res.code === 0) {
        setGameList(res.data.records);
        setFilteredGames(res.data.records);
      } else {
        message.error("获取游戏列表失败");
      }
    } catch (error) {
      message.error("获取游戏列表失败");
    } finally {
      setLoading(false);
    }
  }

  async function getCategoryList() {
    try {
      const res: any = await getCategoryListApi();
      if (res.code === 0) {
        res.data.records.unshift({ id: "all", categoryName: "全部游戏" });
        setGameCategoryList(res.data.records);
      } else {
        message.error("获取游戏分类失败");
      }
    } catch (error) {
      message.error("获取游戏分类失败");
    }
  }

  useEffect(() => {
    getGameList();
    getCategoryList();
  }, []);

  // 筛选和排序游戏
  useEffect(() => {
    let result = [...gameList];

    // 按搜索词筛选
    if (searchTerm) {
      result = result.filter((game: any) =>
        game.title.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    // 按分类筛选
    if (categoryFilter !== "all") {
      result = result.filter((game: any) => game.category === categoryFilter);
    }

    // 排序
    switch (sortOption) {
      case "newest":
        result.sort(
          (a: any, b: any) =>
            new Date(b.releaseDate).getTime() -
            new Date(a.releaseDate).getTime()
        );
        break;
      case "price-low":
        result.sort((a: any, b: any) => a.price - b.price);
        break;
      case "price-high":
        result.sort((a: any, b: any) => b.price - a.price);
        break;
      case "rating":
        result.sort((a: any, b: any) => b.rating - a.rating);
        break;
      default: // popular
        result.sort((a: any, b: any) => b.popularity - a.popularity);
    }

    setFilteredGames(result);
  }, [gameList, searchTerm, categoryFilter, sortOption]);

  const handleGameClick = (gameId: string) => {
    navigate(`/game/game_info/${gameId}`);
  };

  return (
    <div className={style.communityContainer}>
      <h1 className={style.pageTitle}>游戏</h1>

      {/* 筛选控制栏 */}
      <div className={style.filterBar}>
        {/* 分类标签页 - 使用新的items API */}
        <Tabs
          activeKey={categoryFilter}
          onChange={setCategoryFilter}
          className={style.categoryTabs}
          items={categoryItems}
        />

        <div className={style.filterControls}>
          {/* 搜索框 */}
          <Search
            placeholder="搜索游戏名称"
            allowClear
            enterButton
            onSearch={(value) => setSearchTerm(value)}
            className={style.searchInput}
          />

          {/* 排序选择器 */}
          <Select
            defaultValue="popular"
            style={{ width: 150 }}
            onChange={setSortOption}
            className={style.sortSelect}
          >
            <Option value="popular">人气排序</Option>
            <Option value="newest">最新发布</Option>
            <Option value="rating">最高评分</Option>
            <Option value="price-low">价格从低到高</Option>
            <Option value="price-high">价格从高到低</Option>
          </Select>
        </div>
      </div>

      {/* 游戏列表 */}
      <Spin spinning={loading}>
        {filteredGames.length > 0 ? (
          <Row gutter={[16, 16]} className={style.gameGrid}>
            {filteredGames.map((item: any) => (
              <Col
                key={item.id}
                xs={24}
                sm={12}
                md={8}
                lg={6}
                xl={4}
                onClick={() => handleGameClick(item.id)}
              >
                <div className={style.gameCard}>
                  <div className={style.imageContainer}>
                    <img
                      src={item.coverImage || "/default-game.jpg"}
                      alt={item.title}
                      className={style.gameImage}
                    />
                    <div className={style.gameOverlay}>
                      <span className={style.gamePrice}>
                        {item.price ? `¥${item.price}` : "免费"}
                      </span>
                      {item.isNew && (
                        <span className={style.newBadge}>新游</span>
                      )}
                    </div>
                  </div>
                  <div className={style.gameInfo}>
                    <h3 className={style.gameTitle}>{item.title}</h3>
                    <div className={style.gameMeta}>
                      <span className={style.gameRating}>
                        ⭐ {item.rating?.toFixed(1) || "5.0"}
                      </span>
                      <span className={style.gameCategory}>
                        {/* {item.categoryName || item.category} */}
                      </span>
                    </div>
                  </div>
                </div>
              </Col>
            ))}
          </Row>
        ) : (
          <div className={style.noResults}>
            <img
              src="/no-results.svg"
              alt="无结果"
              className={style.noResultsImage}
            />
            <p>没有找到符合条件的游戏</p>
            <button
              className={style.resetButton}
              onClick={() => {
                setSearchTerm("");
                setCategoryFilter("all");
              }}
            >
              重置筛选条件
            </button>
          </div>
        )}
      </Spin>
    </div>
  );
}
